import React, { useState, useEffect } from "react";
import "./home.search.less";
import { getNavList } from "@/api/index.ts";

export default function Search(props) {
  const [list, setList] = useState([]);
  const [isActive, setisActive] = useState(0);

  useEffect(() => {
    // 缓存读取
    if (localStorage.getItem("navList")) {
      setList(JSON.parse(localStorage.getItem("navList")));
    } else {
      getList();
    }
    setNavValue();
  }, []);

  // 向父组件传递导航id
  const setNavValue = () => {
    props.setNavId(isActive);
  };

  // 点击导航切换选中状态
  const handleClick = (id) => {
    setisActive(id);
    setNavValue();
  };

  //  获取导航列表数据
  const getList = async () => {
    const res = await getNavList();
    setList(res.data.channels);
    // 缓存本地
    localStorage.setItem("navList", JSON.stringify(res.data.channels));
  };

  return (
    <div className="search-wrapper">
      <ul>
        {list.map((item) => {
          return (
            <li
              onClick={(_) => handleClick(item.id)}
              key={item.id}
              className={isActive == item.id ? "active" : ""}
            >
              {item.name}
            </li>
          );
        })}
      </ul>
    </div>
  );
}
